package cn.tedu.order.service.impl;

import cn.tedu.order.entity.AccountMessage;
import cn.tedu.order.entity.Order;
import cn.tedu.order.entity.TxInfo;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.service.OrderService;
import cn.tedu.order.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.aspectj.weaver.ast.Var;
import org.bouncycastle.i18n.MessageBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Service
@RocketMQTransactionListener //注册监听器
@Slf4j
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private TxMapper txMapper;

    @Autowired
    private RocketMQTemplate t;

    @Override
    public void create(Order order) {
        //业务方法中,不直接执行业务,而是发送事务消息

        //随机产生xid,uuid是36位字符:t34t-y4-35ty3-34-t34,把减号去掉保留32位
        String xid = UUID.randomUUID().toString().replace("-", "");
        //创建 AccountMessage 封装消息数据: userId,money,xid
        AccountMessage am = new AccountMessage(order.getUserId(), order.getMoney(), xid);
        //消息转成json
        String json = JsonUtil.to(am);
        //把json封装到Spring的通用message对象
        Message<String> msg = MessageBuilder.withPayload(json).build();
        //RocketTemplate发送事务信息
        //t.sendMessageInTransaction("orderTopic", msg,传递到监听器的业务数据参数);
        t.sendMessageInTransaction("orderTopic", msg,order);
    }

    public void doCreate(Order order) {
        //远程调用发号器,获取id
        Map<String, String> map = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(map.get("data"));

        order.setId(orderId);
        orderMapper.create(order);

    }
    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        RocketMQLocalTransactionState state; //用来返回
        int status;                          //存储到数据库
        try {
            //创建订单
            Order order = (Order) o;
            doCreate(order);
            state = RocketMQLocalTransactionState.COMMIT;
            status = 0;
        }catch (Exception e){
            log.error("创建订单失败", e);
            state = RocketMQLocalTransactionState.ROLLBACK;
            status = 1;
        }
        //status插入数据库表tx_table
        //从message取出xid
        String s = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(s, "xid");
        //创建TxInfo对象,保存到数据库表
        txMapper.insert(new TxInfo(xid,status,System.currentTimeMillis()));
        return state;
    }
    //处理rocketmq事务状态回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //从message取出xid
        String s = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(s, "xid");
        //从数据库查询事务的状态
        TxInfo txInfo = txMapper.selectById(xid);
        if (txInfo == null){
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()){
            case 0: return RocketMQLocalTransactionState.COMMIT;
            case 1: return RocketMQLocalTransactionState.ROLLBACK;
            default: return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
